import {Restivus} from 'meteor/nimble:restivus';
import {Meteor} from 'meteor/meteor';
import { Random } from 'meteor/random';
import {Families} from '../imports/api/families';
import {Gateways} from '../imports/api/gateways';
import {OtherDevices} from '../imports/api/other_devices';
// const mqttUrl = '119.254.97.31';
const mqttUrl = 'nodeapis.miitzc.com';
// const mqttUrl = '192.168.89.35';
import { HTTP } from 'meteor/http';
if (Meteor.isServer) {
    Meteor.startup(() => {
        let Api = new Restivus({
            useDefaultAuth: true,
            prettyJson: true,
        });
        // 获取登录用户的网关信息
        Api.addRoute('getGateways', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const devId = param.devId;
                    const sel = {};
                    if(devId && devId != ''){
                        sel['devId'] = devId;
                    }
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    sel['createdName'] = user.username;
                    // if(user) {
                    const gateways = Gateways.find(sel).fetch();
                    return {success: true, result: gateways, resultCode: 1000};
                    // }else{
                    //     return {success: false, result: '请登录！', resultCode: 1004};
                    // }
                }
            }
        });
        // 家庭的默认网关
        Api.addRoute('getDefaultGateway', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const fId = param.familyId;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user){
                        const gateway = Gateways.findOne({isDefault: true, familyId: fId});
                        if(gateway) {
                            return {success: true, result: {gateway: gateway || {}, error: ''}, resultCode: 1000};
                        }else{
                            return {success: false, result: {error: '没有获取到默认网关信息！'}, resultCode: 1000};
                        }

                    }else{
                        return {success: false, result: {error: '请登录!'}, resultCode: 1004};
                    }

                }
            }
        });
        // 切换默认网关
        Api.addRoute('changeDefaultGateway', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const fId = param.familyId;
                    const gtId = param.gatewayId;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user){
                        console.log('param : ', param);
                        const gateway = Gateways.update({devId: gtId, familyId: fId}, {$set: {isDefault: true}});
                        if(gateway) {
                            const gts = Gateways.find({familyId: fId}).fetch();
                            console.log('gts : ', gts);
                            gts.forEach((gt) => {
                                if(gt.devId != gtId){
                                    Gateways.update({devId: gt.devId}, {$set: {isDefault: false}});
                                }
                            });
                            return {success: true, result: '默认网关设置成功！', resultCode: 1000};
                        }else{
                            return {success: false, result: '默认网关设置失败！', resultCode: 1000};
                        }

                    }else{
                        return {success: false, result: '参数不正确！', resultCode: 1004};
                    }

                }
            }
        });
        // 家庭的网关列表
        Api.addRoute('getGatewaysById', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const fId = param.familyId;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user){
                        const gateways = Gateways.find({familyId: fId}).fetch();
                        if(gateways) {
                            return {success: true, result: {gateways: gateways || [], error: ''}, resultCode: 1000};
                        }else{
                            return {success: false, result: {error: '没有获取到网关列表信息！'}, resultCode: 1000};
                        }

                    }else{
                        return {success: false, result: {error: '请登录!'}, resultCode: 1004};
                    }

                }
            }
        });
        //删除网关数据
        Api.addRoute('delGateWayData', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const devId = param.devId;
                    const devKey = param.devKey;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const gt = Gateways.findOne({devId: devId, devKey: devKey});
                        if(gt){
                            const del = Gateways.remove(gt._id);
                            if(del == 1){
                                return  {success: true, result: '网关删除成功', resultCode: 1000};
                            }else{
                                return  {success: true, result: '网关删除失败', resultCode: 1004};
                            }
                        }else{
                            return  {success: false, result: '网关删除失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        //删除网关
        Api.addRoute('deleteGateWay', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const gatewaysId = param.gatewaysId;
                    const devKey = param.devKey;
                    const familyId = param.familyId;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        try {
                            const result = HTTP.call('POST', `http://${mqttUrl}/delGateway`, {
                                data: { admin: user.username, gatewaysId: gatewaysId, devKey: devKey}
                            });
                            console.log('result : ', result);
                            const content = JSON.parse(result.content);
                            if(content.success){
                                const gts = Gateways.find({familyId: familyId}).fetch();
                                if(gts.length > 0){
                                    const gt = gts[0];
                                    Gateways.update({devId: gt.devId}, {$set: {isDefault: true}});
                                }
                                return  {success: true, result: '网关删除成功', resultCode: 1000};
                            }else{
                                return  {success: false, result: '网关删除失败！', resultCode: 1004};
                            }
                        } catch (e) {
                            return  {success: false, result: '网关删除失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        //删除设备
        Api.addRoute('deleteDevice', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const devType = param.devType;
                    const productNumber = param.productNumber;
                    const devID = param.devID;
                    const gatewaysId = param.gatewaysId;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        try {
                            const result = HTTP.call('POST', `http://${mqttUrl}/delDevice`, {
                                data: { admin: user.username, gatewaysId: gatewaysId, devType: devType, productNumber: productNumber, devID: devID}
                            });
                            console.log('result : ', result);
                            const content = JSON.parse(result.content);                            if(content.success){
                                return  {success: true, result: '设备删除成功', resultCode: 1000};
                            }else{
                                return  {success: false, result: '设备删除失败！', resultCode: 1004};
                            }
                        } catch (e) {
                            return  {success: false, result: '设备删除失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        // 添加网关信息前判断，网关是否在该用户下已存在
        Api.addRoute('checkGateway', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const devId = param.devId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gt = Gateways.findOne({devId: devId, createdName: user.username});
                            if(gt){
                                return {success: false, result : '网关已存在，不能添加该网关！', resultCode: 1004};
                            }else{
                                return {success: true, result: '网关信息可以添加！', resultCode: 1000};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
       /* // 修改网关信息
        Api.addRoute('editGateway', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const gtId = param.gatewayId;
                        const deivceId = param.deviceId;
                        console.log('gtId : ', gtId);
                        console.log('deviceId : ', deivceId);
                        if(gtId == ''){
                            return {success: false, result: '没有选中网关信息！', resultCode: 1004};
                        }
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gt = Gateways.findOne({devId: gtId});
                            if(gt){
                                const gty = Gateways.update({devId: gtId},{$set: {isDefault: true}});
                                const dev = Gateways.update({devId: gtId, 'devices.d_id': deivceId},{$set: {'devices.$.isDef': true}});
                                Gateways.update({createdName: user.username,  devId : { $ne : gtId }}, {$set: {isDefault: false}}, false, true);
                                Gateways.update({_id: gt._id, 'devices.d_id' : { $ne : deivceId }}, {$set: {'devices.$.isDef': false}}, false, true);
                                const gateway = Gateways.findOne({devId: gtId});
                                console.log('devices : ', gateway.devices);
                                const devices = gateway.devices;
                                Gateways.update({_id: gateway}, {$set: {'devices': []}});
                                devices.forEach((dev) => {
                                    if(dev.d_id == deivceId){
                                        dev.isDef = true;
                                    }else{
                                        dev.isDef = false;
                                    }
                                });
                                Gateways.update({_id: gateway}, {$pushAll: {'devices': devices}});
                                if(gty && dev){
                                    return {success: true, result: '网关信息修改成功！',resultCode: 1000};
                                }else{
                                    return {success: false, result: '网关信息修改失败！', resultCode: 1004};
                                }
                            }else{
                                return {success: false, result: '要修改的网关信息不存在！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });*/
        // 获取网关添加结果
        Api.addRoute('getAddGateway', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const familyId = param.familyId;
                    const devId = param.id;
                    const telephone = param.telephone;
                    console.log('getAddGateway : ', param);
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const gts = Gateways.findOne({createdName: telephone, devId: devId});
                        if(gts){
                            const gateway = Gateways.findOne({familyId: familyId, isDefault: true});
                            let isDef = false;
                            if(!gateway){
                                isDef = true;
                            }
                            Gateways.update({_id: gts._id}, {$set: {familyId: familyId, isDefault: isDef}});
                            return {success: true, result: '网关添加成功！', resultCode: 1000}
                        }else{
                            return {success: false, result: '网关添加失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        // 获取PIN码
        Api.addRoute('getPinDevice', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const telephone = param.telephone;
                    const gtId = param.gatewayId;
                    console.log('getPinDevice : ', param);
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const gt = Gateways.findOne({devId: gtId,  $or:[{'devices.d_id': ""}, {'devices.d_id': {$exists: false}}],createdName: telephone });
                        if(gt){
                            const devices = gt.devices;
                            const dev = devices.find(function (x) {
                                return (x.d_id == '' || !x.d_id) && x.pin != '';
                            });
                            if(dev){
                                return {success: true, result: dev.pin, resultCode: 1000}
                            }else{
                                return {success: false, result: '获取PIN失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '获取PIN失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        // 获取device
        Api.addRoute('getDeviceMsg', {authRequired: false}, {
            post: { 
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const productNumber = param.productNumber;
                    const gtId = param.gatewayId;
                    const rId = param.roomId;
                    const rName = param.roomName;
                    const num = param.num;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    console.log('getDeviceMsg : ', param, '------'+new Date());
                    if(user) {
                        const gts = Gateways.findOne({devId: gtId});
                        if(gts){
                            //其它设备
                            if(parseInt(num) == 10){
                                // const oDev = OtherDevices.findOne({gatewayId: gts.devId,  c_date: { $gte: new Date(startTime)}});
                                const oDev = OtherDevices.findOne({gatewayId: gts.devId,  productNumber: productNumber, $or:[{roomId: ""}, {roomId: {$exists: false}}]});
                                if(oDev){
                                    OtherDevices.update({_id: oDev._id}, {$set: {roomId: rId, roomName: rName}});
                                    return {success: true, result: oDev.d_id, resultCode: 1000}
                                }else{
                                    return {success: false, result: '设备添加失败！', resultCode: 1004};
                                }
                            }else{ //正常设备
                                const devices = gts.devices;
                                const devs = devices.filter(function(x){
                                    return x.productNumber == productNumber && x.roomId == '' && x.d_id != '' && (x.pin != '' || !x.pin);
                                });
                                console.log('param : ', param);
                                console.log('devs : ', devs);
                                console.log('length : ', devs.length);
                                if(devs && devs.length == parseInt(num)){
                                    let id = '';
                                    devs.forEach((dev) => {
                                        id = dev.d_id;
                                        devices.forEach((device) => {
                                            if(id == device.d_id){
                                                device['roomId'] = rId;
                                                device['roomName'] = rName;
                                            }
                                        });
                                    })

                                    Gateways.update({_id: gts._id}, {$set: {devices: devices}});
                                    return {success: true, result: id, resultCode: 1000}
                                }else{
                                    console.log('ssssssss: ');
                                    return {success: false, result: '设备添加失败！', resultCode: 1004};
                                }
                            }
                        }else{
                            return {success: false, result: '设备添加失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });

        // 修改device
        Api.addRoute('updateDevice', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    console.log('param : ', param);
                    const logintoken = param.token;
                    const name = param.name;
                    const d_id = param.d_id;
                    const channel = param.channel;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const gts = Gateways.findOne({'devices.d_id': d_id, 'devices.ailse': parseInt(channel) });
                        if(gts){
                            const devices = gts.devices;
                            devices.forEach((device) => {
                                if(d_id == device.d_id && device.ailse == parseInt(channel)){
                                    device['d_name'] = name;
                                }
                            });
                            Gateways.update({_id: gts._id}, {$set: {devices: devices}});
                            return {success: true, result: '设备修改成功！', resultCode: 1000}
                        }else{
                            return {success: false, result: '设备修改失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        // 修改other_device
        Api.addRoute('updateOtherDevice', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const name = param.name;
                    const d_id = param.d_id;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const oDev = OtherDevices.findOne({'d_id': d_id});
                        if(oDev){
                            OtherDevices.update({_id: oDev._id}, {$set: {d_name: name}});
                            return {success: true, result: '设备修改成功！', resultCode: 1000}
                        }else{
                            return {success: false, result: '设备修改失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        //根据房间ＩＤ获取其它设备
        Api.addRoute('getOtherDeviceByRoom', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const id = param.id;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        const oDevs = OtherDevices.find({'roomId': id}).fetch();
                        if(oDevs){
                            return {success: true, result: {OtherDevices: oDevs, error: ''}, resultCode: 1000}
                        }else{
                            return {success: false, result: {error: '设备添加失败！'}, resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                    }
                }
            }
        });

        // 请求添加设备
        Api.addRoute('requestAddDevice', {authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const gtId = param.gatewayId;
                    const num = param.productNumber;
                    const phone = param.phone;
                    const type = param.devType;
                    const manufacturer = param.manufacturer;
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        try {
                            const result = HTTP.call('POST', `http://${mqttUrl}/addDevice`, {
                                data: { phone: phone, gatewaysId: gtId, productNumber: num, devType: type, manufacturer: manufacturer }
                            });
                            console.log('result : ', result);
                            const content = JSON.parse(result.content);
                            if(content.success){
                                return  {success: true, result: '请求成功', resultCode: 1000};
                            }else{
                                return  {success: false, result: '请求失败！', resultCode: 1004};
                            }
                        } catch (e) {
                            return  {success: false, result: '请求失败！', resultCode: 1004};
                        }
                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        //修改网关名
        Api.addRoute('editGatewayName', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const gtId = param.gatewayId;
                        const name = param.name;
                        const devName = param.devName;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gt = Gateways.findOne({devId: gtId});
                            if(gt){
                                const gty = Gateways.update({devId: gtId},{$set: {name: name, devName: devName}});
                                if(gty){
                                    return {success: true, result: '网关信息修改成功！',resultCode: 1000};
                                }else{
                                    return {success: false, result: '网关信息修改失败！', resultCode: 1004};
                                }
                            }else{
                                return {success: false, result: '要修改的网关信息不存在！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        //修改设备名
        Api.addRoute('editDeviceName', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const name = param.name;
                        const roomId = param.roomId;
                        const roomName = param.roomName;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gt = Gateways.findOne({'devices.d_id': deviceId});
                            if(gt){
                                const devices = gt.devices;
                                devices.forEach((dev) => {
                                    if(dev.d_id == deviceId){
                                        dev.d_name = name;
                                        dev['roomId'] = roomId;
                                        dev['roomName'] = roomName;
                                    }
                                });
                                const gty = Gateways.update({'_id': gt._id},{$set: {'devices': devices}});
                                console.log('gty : ', gty);
                                if(gty == 1){
                                    return {success: true, result: '设备信息修改成功！',resultCode: 1000};
                                }else{
                                    return {success: false, result: '设备信息修改失败！', resultCode: 1004};
                                }
                            }else{
                                return {success: false, result: '要修改的设备信息不存在！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        //获取网关信息
        Api.addRoute('gatewayInfo', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const gtId = param.gatewayId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gt = Gateways.findOne({'devId': gtId}, {fields: {name: 1, devId: 1, devKey: 1, createdName: 1, mqtt_msg: 1, isDefault: 1, updatedAt: 1, createdAt: 1}});
                            if(gt){
                                return {success: true, result: {gateway: gt, error: ''},resultCode: 1000};
                            }else{
                                return {success: false, result: {error: '没有获取到网关信息!'}, resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有填写注册信息！'}, resultCode: 1002};
                }
            }
        });
        // 获取device信息
        Api.addRoute('deviceInfo',{authRequired: false}, {
            post: {
                action() {
                    const param = this.bodyParams;
                    const logintoken = param.token;
                    const deviceId = param.deviceId;
                    const channel = param.channel;
                    console.log('param: : ', param);
                    const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                    if(user) {
                        if(channel && parseInt(channel) == 10){
                            const oDevs = OtherDevices.find({d_id: deviceId}).fetch();
                            if(oDevs){
                                return {success: true, result: oDevs, resultCode: 1000}
                            }else {
                                return {success: false, result: [], resultCode: 1004};
                            }
                        }else{
                            const gts = Gateways.find({ 'devices.d_id': deviceId}).fetch();
                            console.log('gts : ', gts);
                            if(gts.length > 0){
                                const devices = gts[0].devices;
                                const devs = devices.filter(function (x) {
                                    return x.d_id == deviceId;
                                });
                                return {success: true, result: devs, resultCode: 1000}
                            }else{
                                return {success: false, result: [], resultCode: 1004};
                            }
                        }

                    }else{
                        return {success: false, result: '请登录！', resultCode: 1004};
                    }
                }
            }
        });
        //设备开关操作。
        Api.addRoute('deviceAction', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const gatewayId = param.gatewayId;
                        const operate = param.operate;
                        const channel = param.channel;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/controlDevice`, {
                                    data: { deviceId: deviceId, status: operate, gatewayId: gatewayId, channel: channel}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '操作请求成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '操作请求失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                // Got a network error, timeout, or HTTP error in the 400 or 500 range.
                                return  {success: false, result: '操作请求失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        //指令开锁。
        Api.addRoute('voiceOpenDevice', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.familyId;
                        const str = param.voice;
                        console.log('voice : ', str);
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            try {
                                const gts = Gateways.find({familyId: fId}).fetch();
                                let devs = [];
                                let arr = [];
                                gts.forEach((gt) => {
                                    if(gt.devices){
                                        gt.devices.forEach((dev) => {
                                            arr.push(dev.d_name);
                                            if(str.indexOf('所有') != -1 || str.indexOf(dev.d_name) != -1){
                                                if(dev.isSensor == false){
                                                    devs.push(dev);
                                                }
                                            }
                                        })
                                    }
                                });
                                console.log('arr : ', arr);
                                let operate = 0;
                                if(str.indexOf('开') != -1){
                                    operate = 1;
                                }else if(str.indexOf('关') != -1){
                                    operate = 0;
                                }
                                if(devs.length == 0){
                                    return  {success: false, result: `语音操作未识别，请确认--(${str})!`, resultCode: 1000};
                                }else{
                                    const result = HTTP.call('POST', `http://${mqttUrl}/voiceControlDevice`, {
                                        data: { devices: devs, status: operate}
                                    });
                                    const content = JSON.parse(result.content);
                                    if (content.success === true) {
                                        return  {success: true, result: '操作请求成功!', resultCode: 1000};
                                    }else{
                                        return  {success: false, result: '操作请求失败！', resultCode: 1004};
                                    }
                                }

                            } catch (e) {
                                // Got a network error, timeout, or HTTP error in the 400 or 500 range.
                                return  {success: false, result: '操作请求失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        //根据房间查询设备。
        Api.addRoute('devicesByRoom', {authRequired: false}, {
            post: {
                action() {
                    if (this. bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const roomId = param.roomId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gws = Gateways.find({'devices.roomId': roomId}).fetch();
                            const devices = [];
                            gws.forEach((gw) => {
                                (gw.devices || []).forEach((dev) => {
                                    if(dev.roomId == roomId){
                                        devices.push(dev);
                                    }
                                })
                            })
                            const oDev = OtherDevices.findOne({roomId: roomId});
                            if(oDev){
                                devices.push({d_name: '其它设备', roomId: roomId, productNumber: '000000abc', roomName: oDev.roomName});
                            }
                            return {success: true, result: {devices: devices, error: ''}, resultCode: 1000}
                        }else{
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有填写注册信息！'}, resultCode: 1002};
                }
            }
        });
        //根据家庭查询设备。
        Api.addRoute('devicesByFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const familyId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gws = Gateways.find({'familyId': familyId}).fetch();
                            let devices = [];
                            gws.forEach((gw) => {
                                devices = devices.concat(gw.devices);
                            })
                            devices = devices.filter((x) => x.isSensor == false);  //过滤传感器
                            return {success: true, result: {devices: devices, error: ''}, resultCode: 1000}
                        }else{
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有填写注册信息！'}, resultCode: 1002};
                }
            }
        });
        //根据家庭查询传感器设备。
        Api.addRoute('sensorsByFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const familyId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const gws = Gateways.find({'familyId': familyId}).fetch();
                            let devices = [];
                            gws.forEach((gw) => {
                                devices = devices.concat(gw.devices);
                            })
                            devices = devices.filter((x) => x.isSensor == true);  //选择出传感器
                            return {success: true, result: {devices: devices, error: ''}, resultCode: 1000}
                        }else{
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有填写注册信息！'}, resultCode: 1002};
                }
            }
        });
        //给情景的每个开关添加设备
        Api.addRoute('addSensorSwitchContarl', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const deviceId = param.deviceId;
                        const channel = param.channel;
                        const controlId = param.controlId;
                        const type = param.type;
                        const name = param.name;
                        const status = param.status;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/sensorSwitchContarl`, {
                                    data: { deviceId: deviceId, channel: channel, controlId: controlId, type: type, status: status, name: name }
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: '设备添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: '设备添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '设备添加失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        //添加GPRS网关
        Api.addRoute('addGprsGateway', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const admin = param.admin;
                        const token = param.token;
                        const gatewayId = param.gatewayId;
                        const devKey = param.devKey;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        if(user) {
                            try {
                                const result = HTTP.call('POST', `http://${mqttUrl}/addGPRS`, {
                                    data: { admin: admin, gatewayId: gatewayId, devKey: devKey}
                                });
                                const content = JSON.parse(result.content);
                                if (content.success === true) {
                                    return  {success: true, result: 'GPRS网关添加成功!', resultCode: 1000};
                                }else{
                                    return  {success: false, result: 'GPRS网关添加失败！', resultCode: 1004};
                                }
                            } catch (e) {
                                return  {success: false, result: '设备添加失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
    });
}